package com.cskaoyan.service;

import com.cskaoyan.mapper.AccountMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionCallbackWithoutResult;
import org.springframework.transaction.support.TransactionTemplate;

@Service
public class AccountServiceImpl implements AccountService{
    @Autowired
    AccountMapper accountMapper;

    @Autowired
    TransactionTemplate transactionTemplate;

    @Override
    public void transfer(Integer fromId, Integer destId, Integer money) {
        //查询fromId和destId对应的money
        Integer fromMoney = accountMapper.selectMoneyById(fromId);
        Integer destMoney = accountMapper.selectMoneyById(destId);
        //计算一下转账money之后fromId和destId对应的money
        fromMoney -= money;
        destMoney += money;

        Integer finalFromMoney = fromMoney;
        Integer finalDestMoney = destMoney;
        //Object execute = transactionTemplate.execute(new TransactionCallback<Object>() {
        //    @Override
        //    public Object doInTransaction(TransactionStatus transactionStatus) {
        //        //更新money
        //        accountMapper.updateMoneyById(fromId, finalFromMoney);
        //        int i = 1 / 0;
        //        accountMapper.updateMoneyById(destId, finalDestMoney);
        //        return "songge";//doInTransaction的返回值会给到execute
        //    }
        //});
        //System.out.println(execute);//songge

        //如果你不需要返回值，需要增加事务的这部分代码不需要返回值
        transactionTemplate.execute(new TransactionCallbackWithoutResult() {
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus) {
                //更新money
                accountMapper.updateMoneyById(fromId, finalFromMoney);
                int i = 1 / 0;
                accountMapper.updateMoneyById(destId, finalDestMoney);
            }
        });

    }
}
